<template>
  <div>
    <cus-search style="min-width: 1200px">
      <cus-search-item>
        <Form :model="form" :label-width="80" ref="formValidate" @keydown.native.enter.prevent="onInit">
          <FormItem label="入库日期" class="mr_48 mb_20">
            <el-date-picker :clearable="false" type="week" format="yyyy 第 WW 周" placeholder="请选择"
              v-model="form.dateTime" @change="sDateChange" transfer :picker-options="{ firstDayOfWeek: 1 }"
              style="width: 200px; z-index: 9999">
            </el-date-picker>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="供应商" :label-width="100" prop="supplierId">
            <Select placeholder="全部" clearable v-model="form.supplierId" style="width: 200px">
              <Option v-for="item in supplierNameTree" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="物资分类" :label-width="100" prop="goodsTypeName">
            <Select placeholder="请选择物资分类" v-model="form.goodsTypeName" clearable style="width: 200px">
              <Option :value="''">全部</Option>
              <Option v-for="item in materialTypeList" :value="item.categoryName" :key="item.categoryName">
                {{ item.categoryName }}</Option>
            </Select>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="存储仓库" :label-width="100" prop="stockId">
            <Select placeholder="全部" clearable v-model="form.stockId" style="width: 189px">
              <Option v-for="item in storehouseTree" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </FormItem>
          <FormItem class="mr_48 mb_20" label="物资名称" prop="goodsName">
            <Input placeholder="请输入物资名称" maxlength="20" clearable v-model="form.goodsName" style="width: 200px" />
          </FormItem>
          <cusButton class="mr_20 mb_20" type="primary" @onClick="onQuery()">查询</cusButton>
          <cusButton class="mr_20 mb_20" type="primary" @onClick="reset()">重置</cusButton>
        </Form>
      </cus-search-item>
    </cus-search>
    <cus-card style="margin-top: 20px; padding-top: 20px" :showTitle="false">
      <div class="btnBox">
        <cusButton class="mr_20" type="primary" @onClick="postApiPurchasingExportSummaryListApi()" style="width: 150px">
          导出</cusButton>
        <!-- <cusButton class="mr_20" type="error" @onClick="onPreview()"
        style="width:150px;"
          >打印</cusButton
        > -->
      </div>
      <cusTable border :loading="loading" :columns="columns" :data="data" :size="vuex_config.tableSize"
        :bottomClass="['cus-page', 'cus_operBox']">
      </cusTable>
      <div class="cus_page">
        <cus-page :data="pages" class="mt_20" @pageChange="selectApiGoodsStockbillSummaryListApi()"></cus-page>
      </div>
    </cus-card>
    <!--底部返回-->
    <div class="cus_operBox" style="width: calc(100% - 250px)">
      <Button type="error" class="mr_24" @click="onReturn()">返回</Button>
    </div>
  </div>
</template>

<script>
import {
  getApiGoodsHandaworkSuppliername,
  getBasstockList,
  selectApiGoodsStockbillSummaryList,
  postApiPurchasingExportSummaryList,

} from "@/api/business/manager";
import {

  getProductCategory,

} from "@/api/business/dishesModule";
const columns = [
  {
    title: "序号",
    type: "index",
    align: "center",
    fixed: "left",
    minWidth: 70
  },
  {
    title: "物资名称",
    key: "goodsName",
    minWidth: 134,
    fixed: "left",
    align: "center"
  },
  {
    title: "物资分类",
    key: "goodsTypeName",
    minWidth: 125,
    align: "center"
  },
  {
    title: "物资编码",
    key: "goodsCode",
    minWidth: 125,
    align: "center"
  },
  {
    title: "供应商",
    key: "supplierName",
    minWidth: 125,
    align: "center"
  },
  {
    title: "存储仓库",
    key: "stockName",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周一",
    key: "monday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周二",
    key: "tuesday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周三",
    key: "wednesday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周四",
    key: "thursday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周五",
    key: "friday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周六",
    key: "saturday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "周日",
    key: "sunday",
    minWidth: 125,
    align: "center"
  },
  {
    title: "合计数量",
    key: "total",
    minWidth: 125,
    align: "center"
  },
  {
    title: "单位重量(Kg)",
    key: "unitWeight",
    minWidth: 125,
    align: "center"
  },
  {
    title: "单价(元)",
    key: "packagingPrice",
    minWidth: 125,
    align: "center"
  },
  {
    title: "计量单位",
    key: "specification",
    minWidth: 125,
    align: "center"
  },
  {
    title: "金额(元)",
    key: "amount",
    minWidth: 125,
    align: "center"
  }
];

export default {
  name: "",
  data() {
    return {
      loading: false,
      ruleValidate: {},
      dateStr: [],
      form: {
        id: "",
        startDate: "", // 开始时间
        stopDate: "", // 结束时间
        supplierId: "", // 供应商id
        stockId: "", // 存储仓库id
        goodsName: "", // 物资名称
        goodsTypeName: "", // 物资分类
        dateTime: ""
      },
      exportForm: {

      },
      columns,
      data: [],
      supplierNameTree: [], // 供应商名称selectTree数据
      storehouseTree: [], // 存储仓库selectTree数据
      materialTypeList: [], // 物资种类Select数据
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      tableHeight: 0
    };
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 490; // 表格自适应高度
    }, 100);
    window.addEventListener("resize", this.tableHeightChange, true);
    this.onInit();
  },
  destroyed() {
    window.removeEventListener("resize", this.tableHeightChange, true);
  },
  methods: {
    onInit() {
      this.getProductCategoryApi();
      this.getCurrentWeek(new Date().Format("yyyy-MM-dd"));
      this.getBasstockListApi();
      this.getApiGoodsHandaworkSuppliernameApi();
      this.selectApiGoodsStockbillSummaryListApi();
    },
    onQuery() {
      this.pages.page = 1
      this.exportForm = this.$cu.deepClone(this.form)
      this.selectApiGoodsStockbillSummaryListApi();
    },
    // 重置搜索
    reset() {
      this.form.supplierId = "";
      this.form.stockId = "";
      this.form.goodsName = "";
      this.form.goodsTypeName = "";
      this.dateStr = [];
      this.form.startDate = "";
      this.form.stopDate = "";
      this.$refs["formValidate"].resetFields();
      this.onInit();
    },
    // DatePicker事件(起止日期)
    onChange(e) {
      this.dateStr = e;
      (this.form.startDate = e[0]), // 开始日期
        (this.form.stopDate = e[1]); // 结束日期
    },
    onPreview() {
      window.print();
    },
    // 返回
    onReturn() {
      window.history.go(-1);
    },
    // DatePicker事件(起止日期)
    sDateChange(time) {
      this.form.startDate = this.getCurrentWeek(time)[0];
      this.form.stopDate = this.getCurrentWeek(time)[6];


    },

    // 获取本周日期组件处理
    getCurrentWeek(date) {
      let nowData = new Date(date); //传入时间参数,如 2021-11-09 获取给定日期所属的周 日期
      let currentDay = nowData.getDay();
      if (currentDay == 0) {
        currentDay = 7;
      }
      let beforweek = [],
        afterWeek = [];
      for (let i = 1; i <= 7; i++) {
        if (currentDay - i >= 0) {
          let DayTime = nowData.getTime() - (currentDay - i) * 24 * 60 * 60 * 1000;
          beforweek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        } else {
          let DayTime = nowData.getTime() + (8 - i) * 24 * 60 * 60 * 1000;
          afterWeek.push(new Date(DayTime).Format("yyyy-MM-dd"));
        }
      }
      afterWeek = afterWeek.reverse();
      let dateList = [...beforweek, ...afterWeek];
      this.form.dateTime = dateList[0]
      this.form.startDate = dateList[0];
      this.form.stopDate = dateList[6];
      console.log(dateList);
      return dateList;
    },
    // 获取供应商名称-------------------接口
    getApiGoodsHandaworkSuppliernameApi() {
      return new Promise(resolve => {
        getApiGoodsHandaworkSuppliername().then(res => {
          if (res.retCode === 2000) {
            this.supplierNameTree = res.data;
            resolve();
          }
        });
      });
    },
    // 物资仓库列表----------------接口
    getBasstockListApi() {
      return new Promise(resolve => {
        let params = {
          current: 1,
          size: 1000
        };
        getBasstockList(params).then(res => {
          if (res.retCode == 2000) {
            this.storehouseTree = res.data.records;
            resolve();
          }
        });
      });
    },
    // 物资入库验收清单报表导出-----------------------接口
    postApiPurchasingExportSummaryListApi() {
      console.log(this.exportForm, this.form);
      window.location.href = `${postApiPurchasingExportSummaryList(
        this.exportForm.startDate,
        this.exportForm.supplierId,
        this.exportForm.goodsTypeName,
        this.exportForm.stockId,
        this.exportForm.goodsName,
      )}&token=${this.$store.state.vuex_user.token}`;
    },
    // 物资入库汇总表-----------------------------接口
    selectApiGoodsStockbillSummaryListApi() {
      this.loading = true;
      this.data = []
      return new Promise(resolve => {
        let params = {
          startDate: this.form.startDate,
          stopDate: this.form.stopDate,
          supplierId: this.form.supplierId,
          goodsTypeName: this.form.goodsTypeName,
          stockId: this.form.stockId,
          goodsName: this.form.goodsName,
          current: this.pages.page,
          size: this.pages.pageSize
        };
        selectApiGoodsStockbillSummaryList(params).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            this.data = res.data.records;
            this.pages.pageTotal = res.data.total;
            resolve();
          } else if (res.retCode === 0) {
            this.$Message.error(res.retMsg);
          }
        });
      });
    },

    // 获取物资分类-----------------接口
    getProductCategoryApi() {
      return new Promise(resolve => {
        getProductCategory().then(res => {
          if (res.code == 1) {
            // console.log(res.data);
            this.materialTypeList = res.result;
            console.log('123', this.materialTypeList);
            resolve();
          }
        });
      });
    }
  },
  watch: {

  }
};
</script>
<style lang="less" scoped>
.btnBox {
  padding-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
